package com.kmxd.ams.app.arrange.command;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.arrange.dto.MergeDocumentDTO;
import com.kmxd.ams.client.arrange.dto.MergeEFileQueryDTO;
import com.kmxd.ams.client.oss.IEfileRecordSvc;
import com.kmxd.ams.client.oss.vo.EfileRecordListVO;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.common.enums.ParamsValidateType;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.exception.ParamsValidateException;
import com.kmxd.ams.core.util.FieldUtil;
import com.kmxd.ams.core.util.IdUtil;
import com.kmxd.ams.infra.arrange.entity.Document;
import com.kmxd.ams.infra.oss.entity.EfileRecord;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合并组件
 *
 * @author nickbi
 */
@Slf4j
@Component
@AllArgsConstructor
public class MergeDocumentCmd {
  private final IDocumentSvc documentSvc;
  private final IEfileRecordSvc fileRecordSvc;

  @Transactional(rollbackFor = Exception.class)
  public void mergeDocument(MergeDocumentDTO req) {
    if (Objects.isNull(req.getId())) {
      throw ParamsValidateException.instance(
          FieldUtil.getFieldName(MergeDocumentDTO::getId), ParamsValidateType.NOT_NULL);
    }

    if (Objects.isNull(req.getDocIds())) {
      throw ParamsValidateException.instance(
          FieldUtil.getFieldName(MergeDocumentDTO::getDocIds), ParamsValidateType.NOT_NULL);
    }

    documentSvc.remove(req);
    Document view =
        Optional.ofNullable(documentSvc.view(req))
            .orElseThrow(() -> BizTipException.instance(ErrorCode.NOT_FOUND, "未找到文档信息"));
    BeanUtil.copyProperties(view, req, CopyOptions.create().setIgnoreNullValue(true));
    documentSvc.edit(req);
    if (StrUtil.isBlank(req.getRecordIds())) {
      return;
    }
    List<EfileRecord> fileRecords = fileRecordSvc.listByIds(IdUtil.split(req.getRecordIds()));
    if (ObjectUtil.isEmpty(fileRecords)) {
      return;
    }
    fileRecords.forEach(fileRecord -> fileRecord.setArchId(req.getId()));
    fileRecordSvc.updateBatchById(fileRecords);
    fileRecordSvc.remove(req.getRemoveRecordIds());
  }

  public List<EfileRecordListVO> getMergeFileList(MergeEFileQueryDTO req) {
    return fileRecordSvc.selectListByDocIds(IdUtil.split(req.getDocIds()));
  }
}
